const express = require('express')
const path = require('path')
const favicon = require('serve-favicon')
const logger = require('morgan')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
// define middleware
const QuickRender = require('./middleware/QuickRender')
// const HistoryRecord = require('./middleware/HistoryRecodrd')
const AutoToken = require('./middleware/AutoToken').auth

// router
const login = require('./routes/login')
const admin = require('./routes/admin')
const file = require('./routes/upload')
// collection
const collection = require('./routes/collection')
// user
const user = require('./routes/users')
// 查询中间件
const SearchCreator = require('./middleware/SearchCreator')

const app = express()


const multer = require('multer')
const upload = multer({ dest: 'uploads/' })


//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

// use middleware
app.use(QuickRender)
// router no auth
app.use('/api', login, admin)

app.use(AutoToken)
app.use('/api/cell', SearchCreator, collection)
app.use('/api', SearchCreator, user)
app.use('/api/upload', AutoToken, file)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  const err = new Error('Not Found')
  err.status = 404
  next(err)
})
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}

  // render the error page
  res.status(err.status || 500)
  throw new Error(err)
})

module.exports = app
